﻿using System;
using System.Collections.Generic;
using System.Linq;
using EntityFrameworkExtension.Interface;

namespace EntityFrameworkExtension.Helper
{
    public class Generic
    {

        public static TU GetId<T, TU>(string name, IEnumerable<T> list) where T : IReferenceTypeMapping<TU> where  TU : struct 
        {
            return (from x in list
                           where x.Name == name
                           select x.Id).FirstOrDefault();
        }

        public static void Populate<T>(T input, Func<T, IEfContext, T> getExisting, Action<T, IEfContext> insert, Action<T, T> update, IEfContext efContext) where T : class
        {
            if (input == null) return;

            var existing = getExisting(input, efContext);

            if (existing == null)
                insert(input, efContext);
            else
                update(existing, input);
        }
    }
}
